package com.sl.au.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder.In;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.AfterSaleTicket;
import com.sl.au.entity.Contract;
import com.sl.au.entity.ContractInfoView;
import com.sl.au.entity.ContractPart;
import com.sl.au.entity.ContractPump;
import com.sl.au.entity.ContractRepair;
import com.sl.au.entity.DateQueryItem;
import com.sl.au.entity.ExdeContractPrudctP;
import com.sl.au.entity.Module;
import com.sl.au.entity.SaleArea;
import com.sl.au.entity.User;
import com.sl.au.service.AfterSaleTicketService;
import com.sl.au.service.ContractService;
import com.sl.au.service.ContractViewService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;

@RestController
@RequestMapping(value = "/ui/contractviewindex")
public class ExdeContractInfoViewController extends BaseController {
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	ContractViewService contractViewService;
	
	@Autowired
	ContractService contractService;
	
	@Autowired
	AfterSaleTicketService afterSaleTicketService;
	
	//片区
	@Autowired
	SaleAreaService saleAreaService;
	
	/**
	 * 合同管理页面显示
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		Module module = this.getPageModule("contractview");
		ModelAndView modelAndView = this.createLayoutView("chartinfo/contractviewindex");
		//modelAndView.addObject("orderArea", contractViewService.getExdeContractViewRepository().getSaleArea());
		System.out.println(request.getParameter("deptName"));
		String[] areaNames = null;
		String[] superiors = null;
		if(StringUtils.hasText(request.getParameter("areaName"))){
			areaNames = request.getParameter("areaName").toString().split(",");//片区
		}
		if(StringUtils.hasText(request.getParameter("deptName"))){
			superiors = request.getParameter("deptName").toString().split(",");//部门
		}
		List<SaleArea> orderAreas = saleAreaService.getRepository().getAllSaleArea();
		List<SaleArea> SaleOrderAreas = new ArrayList<SaleArea>();//销售
		List<SaleArea> CompleteOrderAreas = new ArrayList<SaleArea>();//成套
		List<SaleArea> ForeignOrderAreas = new ArrayList<SaleArea>();//外贸
		for(SaleArea orderArea : orderAreas){
			
			orderArea.setIsSelected(false);
			if(orderArea.getSuperior().equals("销售处")){
				if(superiors!=null&&superiors.length>0){
					if(areaNames!=null&&areaNames.length>0){
						for(int i=0;i<areaNames.length;i++){
							if(areaNames[i].equals(orderArea.getSuperiorArea()))
								orderArea.setIsSelected(true);
						}
					}else{
						for(int i=0;i<superiors.length;i++){
							if(superiors[i].equals(orderArea.getSuperior()))
								orderArea.setIsSelected(true);
						}
					}
				}
				if(orderArea.getAreaName().equals("销售处-分管领导")){
				}else{
					if(orderArea.getAreaName().equals("科长")){
					}else{
						SaleOrderAreas.add(orderArea);
					}
				}
			}
			if(orderArea.getSuperior().equals("成套处")){
				if(superiors!=null&&superiors.length>0){
					if(areaNames!=null&&areaNames.length>0){
						for(int i=0;i<areaNames.length;i++){
							if(areaNames[i].equals(orderArea.getSuperiorArea()))
								orderArea.setIsSelected(true);
						}
					}else{
						for(int i=0;i<superiors.length;i++){
							if(superiors[i].equals(orderArea.getSuperior()))
								orderArea.setIsSelected(true);
						}
					}
				}
				if(orderArea.getAreaName().equals("其他")){
				}else{
					if(orderArea.getAreaName().equals("成套处分管领导")){
					}else{
						CompleteOrderAreas.add(orderArea);
					}
				}
			}
			if(orderArea.getSuperior().equals("外贸处")){
				if(superiors!=null&&superiors.length>0){
					if(areaNames!=null&&areaNames.length>0){
						for(int i=0;i<areaNames.length;i++){
							if(areaNames[i].equals(orderArea.getSuperiorArea()))
								orderArea.setIsSelected(true);
						}
					}else{
						for(int i=0;i<superiors.length;i++){
							if(superiors[i].equals(orderArea.getSuperior()))
								orderArea.setIsSelected(true);
						}
					}
				}
					if(orderArea.getAreaName().equals("外贸处-分管领导")){
					}else{
						ForeignOrderAreas.add(orderArea);
					}
			}
		}
		modelAndView.addObject("SaleOrderAreas", SaleOrderAreas);
		modelAndView.addObject("CompleteOrderAreas", CompleteOrderAreas);
		modelAndView.addObject("ForeignOrderAreas", ForeignOrderAreas);
		
		//modelAndView.addObject("dutyOfficers", optionService.getRepository().findByGroup(request.getParameter("areaName")));//责任人
		
		modelAndView.addObject("industryInfos", optionService.getRepository().findByGroup("行业"));//行业
		/*String industryInfo1 = null;
		if(request.getParameter("industryName")==null){
			industryInfo1 = "";
		}else{
			if(request.getParameter("industryName").equals(""))
				industryInfo1 = "无";
			else
				industryInfo1 = request.getParameter("industryName");
		}*/
		modelAndView.addObject("industryInfo1", request.getParameter("industryName")!=null ? request.getParameter("industryName") : "");//行业
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		modelAndView.addObject("startDate", request.getParameter("beginDate"));//开始时间
		modelAndView.addObject("endDate", request.getParameter("endDate")!=null ? request.getParameter("endDate") : df.format(new Date()));//结束时间
		modelAndView.addObject("nameDate", request.getParameter("dateTimeType")!=null?request.getParameter("dateTimeType"):"");//时间类型

		if(request.getParameter("industryName")!=null || request.getParameter("contractType")!=null || StringUtils.hasText(request.getParameter("areaName")) || StringUtils.hasText(request.getParameter("deptName")))
			modelAndView.addObject("contractState", "正常");//合同状态为正常
		else
			modelAndView.addObject("contractState", "");//合同状态为""
		
		modelAndView.addObject("contractType", request.getParameter("contractType")!=null ? request.getParameter("contractType") : "");//合同类型
		
		String repairKindGroup = "返修类别";
		modelAndView.addObject("repairKinds", optionService.getRepository().findByGroup(repairKindGroup));
		modelAndView.addObject("module", module);
		return modelAndView;
	}
	
	/**
	 * 获取页面数据
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> qMap = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
		Map<String, Object>numMap=new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		Account a = this.getMyAccount();
		//Module module = this.getPageModule("contractInfoView");
		//String dataFilter = module.getDataFilter();
		String dataFilter = "";
		User user = a.getUser();
		this.getQueryParams(qMap,numMap);
		condition.put("qMap", qMap);
		condition.put("numMap", numMap);
		
		String userId = a.getUser().getId();
		String Superior = a.getUser().getSaleArea().getSuperior();//权限部门
		String areaName = a.getUser().getSaleArea().getAreaName();
		if (userId == null) {
			userId = "";
		}
		if (Superior == null) {
			Superior = "";
		}
		if (areaName == null) {
			areaName = "";
		}
		/*if (dataFilter == null) {
			dataFilter = "";
		}*/
		condition.put("userId", userId);
		condition.put("superior", Superior);
		condition.put("areaName", areaName);
		condition.put("dataFilter", dataFilter);
		List<ContractInfoView> contracts = contractViewService.getContractInfos(start, length, condition, user, "createTime", "desc");
		List<ContractInfoView> contractsum = contractViewService.getContractInfos(0, Integer.MAX_VALUE, condition, user, "createTime","desc");
		long count = contractsum.size();
		Double sum = 0.0;
		for(ContractInfoView contract : contractsum){
			sum += contract.getTotalSum();
		}
		map.put("data", contracts);
		map.put("sum", sum);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 计算合同总额
	 */
	@RequestMapping(value = "getPageSum", method = RequestMethod.GET)
	public Map<String, Object> getPageSum(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> qMap = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
		Map<String, Object>numMap=new HashMap<String, Object>();
		Account a = this.getMyAccount();
		//Module module = this.getPageModule("contractInfoView");
		//String dataFilter = module.getDataFilter();
		String dataFilter = "";
		User user = a.getUser();
		this.getQueryParams(qMap,numMap);
		condition.put("qMap", qMap);
		condition.put("numMap", numMap);
		
		String userId = a.getUser().getId();
		String Superior = a.getUser().getSaleArea().getSuperior();//权限部门
		String areaName = a.getUser().getSaleArea().getAreaName();
		if (userId == null) {
			userId = "";
		}
		if (Superior == null) {
			Superior = "";
		}
		if (areaName == null) {
			areaName = "";
		}
		/*if (dataFilter == null) {
			dataFilter = "";
		}*/
		condition.put("userId", userId);
		condition.put("superior", Superior);
		condition.put("areaName", areaName);
		condition.put("dataFilter", dataFilter);
		Double score = contractViewService.getContractSum(condition, user, "createTime", "desc");
		//Integer sum = (Integer)score;
		
		//double s=5.0d;
		//int i=0;
		//Double d_s=new Double(score);
		//int sum=d_s.intValue();
		map.put("sum", new java.text.DecimalFormat("#.00").format(score));
		return map;
	}
	
	private void getQueryParams(Map<String, Object> qMap,Map<String, Object>numMap){
		//String names[]={"superior","orderArea","dutyOfficer","industryInfo","generateState","contractState","contractType"};
		String names[]={"orderArea","industryInfo","state","contractType"};
		String dates[] = {"createTime","signedDate","scheduleDate"};
		//System.out.println(request.getParameter("orderArea").toString().split(","));
		for(String name:names){
			System.out.println(request.getParameter(name));
			if(StringUtils.hasText(request.getParameter(name))){
				String[] a = request.getParameter(name).toString().split(",");
				String b = "";
				for(int i=0;i<a.length;i++){
					b += "'" + a[i] + "',";
				}
				b = b.substring(0, b.length()-1);
				numMap.put(name, b);
			}
			
		}
		if(StringUtils.hasText(request.getParameter("totalSum"))){
			numMap.put("totalSum", request.getParameter("totalSum").toString());
		}
		if(StringUtils.hasText(request.getParameter("cProductProcess"))){
			numMap.put("cProductProcess", request.getParameter("cProductProcess").toString());
		}
		if(StringUtils.hasText(request.getParameter("Contract"))){
			numMap.put("Contract", request.getParameter("Contract").toString());
		}
		for(String date:dates){
			if(null!=this.getDateQueryItem(date)){
				qMap.put(date,this.getDateQueryItem(date));
			}
		}
		
	}
	
	/**
	 * 查看合同
	 */
	@RequestMapping(value = "getcontractview/{contractViewId}/{contractViewType}")
	public ModelAndView getContractView(@PathVariable String contractViewId, @PathVariable String contractViewType) {
		String contractCode = "";
		ModelAndView modelAndView = this.createLayoutView("chartinfo/contractviewsee");
		
		if (contractViewType.equals("备件合同")) {
			//modelAndView = this.createLayoutView("contract/part-contract-edit");
			ContractPart contractPart = null;
			if (contractViewId != null && !contractViewId.equals("")) {
				contractPart = contractService.getContractPartById(contractViewId);
				if (contractPart.getSupplierCode()!=null){
					contractCode = contractPart.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractPart);
		} else if (contractViewType.equals("备泵合同")) {
			//modelAndView = this.createLayoutView("contract/pump-contract-edit");
			ContractPump contractPump = null;
			if (contractViewId != null && !contractViewId.equals("")) {
				contractPump = contractService.getContractPumpById(contractViewId);
				if (contractPump.getSupplierCode()!=null){
					contractCode = contractPump.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractPump);
		} else if (contractViewType.equals("维修合同")) {
			//modelAndView = this.createLayoutView("contract/repair-contract-edit");
			ContractRepair contractRepair = null;
			if (contractViewId != null && !contractViewId.equals("")) {
				contractRepair = contractService.getContractRepairById(contractViewId);
				if (contractRepair.getSupplierCode()!=null){
					contractCode = contractRepair.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractRepair);
		} else {
			Contract contract = null;
			if (contractViewId != null && !contractViewId.equals("")) {
				contract = contractService.getContractById(contractViewId);
				if (contract.getSupplierCode()!=null){
					contractCode = contract.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contract);
		}
		modelAndView.addObject("contractCode", contractCode);
		modelAndView.addObject("contractView", contractViewService.getExdeContractViewRepository().findOne(contractViewId));
		modelAndView.addObject("contractViewType", contractViewType);
		modelAndView.addObject("contractViewId", contractViewId);
		return modelAndView;
	}

	/**
	 * 备件、备泵、维修合同列表
	 */
	@RequestMapping(value = "getbeijianView", method = RequestMethod.GET)
	public Map<String, Object> getBeijianView(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<ContractInfoView> list = null;
		String contractViewId = request.getParameter("contractViewId");
		String contractViewType = request.getParameter("contractViewType");
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		list = contractViewService.getBeijianView(start,length,contractViewId,contractViewType);
		long count = contractViewService.getBeijianViewCount(contractViewId,contractViewType);
		map.put("data", list);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value = "getSpeed", method = RequestMethod.GET)
	public Map<String, Object> getSpeed(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String supplierCode = request.getParameter("supplierCode");
		List<ExdeContractPrudctP> list = contractViewService.getSpeed(supplierCode);
		for(ExdeContractPrudctP lis : list){
			Integer FinishCount = lis.getFinishCount();
			Integer TotalCount = lis.getTotalCount();
			Integer n = TotalCount==0 ? 0 : FinishCount*100/TotalCount;
			if(lis.getViewName().equals("设计")) map.put("sheji", n);//
			if(lis.getViewName().equals("配置")) map.put("peizhi", n);
			if(lis.getViewName().equals("加工")) map.put("jiagong", n);
			if(lis.getViewName().equals("采购")) map.put("caigou", n);
			if(lis.getViewName().equals("外协")) map.put("waixie", n);
			if(lis.getViewName().equals("装配")) map.put("zhuangpei", n);
			if(lis.getViewName().equals("试水")) map.put("shishui", n);
			if(lis.getViewName().equals("油漆")) map.put("youqi", n);
			if(lis.getViewName().equals("封箱")) map.put("fengxiang", n);
		}
		if(list.size()==0){
			map.put("sheji", 0);//TotalCount==0 ? 0 : FinishCount/TotalCount*100
			map.put("peizhi", 0);
			map.put("jiagong", 0);
			map.put("caigou", 0);
			map.put("waixie", 0);
			map.put("zhuangpei", 0);
			map.put("shishui", 0);
			map.put("youqi", 0);
			map.put("fengxiang", 0);
		}
		return map;
	}
	
	/**
	 * 售后列表
	 */
	@RequestMapping(value = "getshouhouView", method = RequestMethod.GET)
	public Map<String, Object> getShouhouView(HttpServletRequest request) {
		String contractViewId = request.getParameter("contractViewId");
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
//		Module module = this.getPageModule("aftersaleticket");
//		String dataFilter = module.getDataFilter();
		Account a = this.getMyAccount();
//		String userId = a.getUser().getId();
//		String roleName = a.getRole().getName();
//		String superior = a.getUser().getSaleArea().getSuperior();
//		String areaId = a.getUser().getSaleArea().getId();
		Map<String, String> condition = new HashMap<String, String>();
//		condition.put("dataFilter", dataFilter);
//		condition.put("userId", userId);
//		condition.put("roleName", roleName);
//		condition.put("superior", superior);
//		condition.put("areaId", areaId);
		condition.put("contractViewId", contractViewId);
		List<AfterSaleTicket> afterSaleTickets = contractViewService.getAfterSaleTicket(start, length, condition,null, null);
		long count = contractViewService.getAfterSaleTicketCount(condition);
		/*List<AfterSaleTicket> newafterSaleTickets=new ArrayList<AfterSaleTicket>();
		for(AfterSaleTicket r : afterSaleTickets){
			String parentId=r.getId();
			List<Attachment> l= attachmentService.getRepository().findByParentId(parentId);
			int num = l.size();
			r.setAttachNumber(num);
			newafterSaleTickets.add(r);
		}*/
		map.put("data", afterSaleTickets);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	

}
